package com.xatu.yl.storeshopping.activity.RegisterAndLogin;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;


import com.xatu.yl.util.NetUtils;
import com.example.namespace.R;

import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class HelloActivity extends AppCompatActivity {
    public static int DELAYTIME = 3; // 延迟时间
    int NewVerCode;
    int localVercode;
    private JSONObject jsonObject = null;
//    private UpdateManager mUpdateManager = null;



    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    checkVersion();
                    break;
                default:
                    break;
            }
        };
    };
    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)){
                return true;
            }else{
                permissionsList.add(permission);
                return false;
            }

        }else{
            return true;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //提前开启获取GPS的服务
        //然后在登录页面获取GPS信息，同时上传
//        Intent i = new Intent(this, GpsService.class);
//        startService(i);



        /**全屏设置，隐藏窗口所有装饰**/
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        /**标题是属于View的，所以窗口所有的修饰部分被隐藏后标题依然有效,需要去掉标题**/
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello);

//			setContentView(R.layout.about2);
        //创建必要的文件夹
//        FileUtils fu = new FileUtils();
//        fu.createSDDir(AppContent.appPath);

//        if(AppContent.isHot){
//            switchIcon(2);
//        }else {
//            switchIcon(1);
//        }
        int SDK_PERMISSION_REQUEST = 127;
        String permissionInfo = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
//            if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
//                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
//            }
            if(checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.CAMERA);
            }

            /*
             * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
             */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

//            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
//                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
//            }


            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }else{
                startService();
            }
        }

    }


    /**
     * 处理权限请求结果
     *
     * @param requestCode
     *          请求权限时传入的请求码，用于区别是哪一次请求的
     *
     * @param permissions
     *          所请求的所有权限的数组
     *
     * @param grantResults
     *          权限授予结果，和 permissions 数组参数中的权限一一对应，元素值为两种情况，如下:
     *          授予: PackageManager.PERMISSION_GRANTED
     *          拒绝: PackageManager.PERMISSION_DENIED
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        for (int i = 0; i < grantResults.length; i++) {
            if (PackageManager.PERMISSION_DENIED == grantResults[i]) {
                Toast.makeText(this, "拒绝权限，无法开启", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        startService();
    }
    protected void startService(){

//        mUpdateManager = new UpdateManager(HelloActivity.this);
//        if(false == NetUtils.isConnected(getApplicationContext())){
//            AppContent.hasAD = false;
//        }
//        if(AppContent.hasAD ){
//        }

        new AsyncTask<Void, Void, Integer>(){//异步任务，进行软件更新等

            @Override
            protected Integer doInBackground(Void... params) {

                //启动后台服务
//                Intent serviceIntent = new Intent(HelloActivity.this, MyService.class);
                //serviceIntent.setAction("com.lanshui.mobile.MYGETPUSH_ORDER_ACTION");
//                serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startService(serviceIntent);
                return 1;
            }

            @Override
            protected void onPostExecute(Integer result) {

            };
        }.execute(new Void[]{});
        //创建必要的文件夹
//			FileUtils fu = new FileUtils();
//			fu.createSDDir(AppContent.picPath);
//			fu.createSDDir(AppContent.AppBasePath+"/checkok");


//			mVersionNameText = (TextView) findViewById(R.id.version_name);
//			mVersionNameText.setText("0.0.1");
        if(NetUtils.isConnected(getApplicationContext())){
            getRemoteVersion();//检测更新
        }else{
//            mUpdateManager.update = false;
        }
        //等待转向

        final Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
//                if(AppContent.servicefinish && mUpdateManager.update == false){
//                    //TODO
//                    //Intent it = new Intent(HelloActivity.this, CheckFaceActivity.class); //你要转向的Activity
//
//                    //db.close();
//                    startActivity(new Intent(HelloActivity.this, LoginActivity.class)); //执行
//                    HelloActivity.this.finish();
//                    timer.cancel();
//                }
            }
        };
        timer.schedule(task, 1000 * DELAYTIME , 1000);
        //等待转向
    }

    protected void checkVersion() {
        try {
            /**
             * 版本更新
             */
//            if(true){
//                localVercode = getPackageManager().getPackageInfo(
//                        "com.xatu.yuexin.welding4slhot", 0).versionCode;
//            }else{
//                localVercode = getPackageManager().getPackageInfo(
//                        "com.xatu.yuexin.welding4slele", 0).versionCode;
//            }

            // 这里来检测版本是否需要更新
            if (NewVerCode > localVercode) {
                String downloadUrl =  jsonObject.getString("downloadUrl") ;
//					"http://www.chongchi-tech.com/ccsoft/uploads/app/SmartHome1.0.16_201410091748.apk";

                String verComment = jsonObject.getString("verComment");

//                mUpdateManager.checkUpdateInfo(downloadUrl, verComment);
            } else {
                Toast.makeText(this, "已是最新版本无需更新！", Toast.LENGTH_SHORT).show();
//                mUpdateManager.update = false;
            }
        } catch (Exception e) {
//            mUpdateManager.update = false;
            e.printStackTrace();
        }
    }

    public void getRemoteVersion() {
        new Thread() {
            public void run() {
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                byte[] data = new byte[1024];
                int len = 0;
                URL url = null;
                try {
//                    url = new URL(
//                            AppContent.updateInfo);
//						Toast.makeText(LogoActivity.this, "http://192.168.1.105:8080/permission/permission/test.mvc", Toast.LENGTH_LONG).show();
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setConnectTimeout(5000);
                    InputStream inStream = conn.getInputStream();
                    while ((len = inStream.read(data)) != -1) {
                        outStream.write(data, 0, len);
                    }
                    inStream.close();
                    String result = new String(outStream.toByteArray(), "GBK");// 通过out.Stream.toByteArray获取到写的数据
//						Toast.makeText(LogoActivity.this, result, Toast.LENGTH_LONG).show();
                    jsonObject = new JSONObject(result);
                    NewVerCode = jsonObject.getInt("verCode");

                    Message msg = new Message();
                    msg.what = 1;
                    mHandler.sendMessage(msg);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
//                    mUpdateManager.update = false;
                    e.printStackTrace();
                }
            };
        }.start();
    }

    /**
     * @param useCode =1、为活动图标 =2 为用普通图标 =3、不启用判断
     */
    private void switchIcon(int useCode) {

        try {
            //要跟manifest的activity-alias 的name保持一致
            String icon_tag = "com.xatu.yuexin.welding4sl.icon_tag";
            String icon_tag_1212 = "com.xatu.yuexin.welding4sl.icon_tag_1212";

            if (useCode != 3) {

                PackageManager pm = getPackageManager();

                ComponentName normalComponentName = new ComponentName(
                        this,
                        icon_tag);
                //正常图标新状态
                int normalNewState = useCode == 2 ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                        : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
                if (useCode == 2) {//新状态跟当前状态不一样才执行

                    //去除旧图标，不去除的话会出现2个App图标
//                    pm.setComponentEnabledSetting(getComponentName(),
//                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
//                            PackageManager.DONT_KILL_APP);
                    pm.setComponentEnabledSetting(
                            normalComponentName,
                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                            PackageManager.DONT_KILL_APP);

                }

                ComponentName actComponentName = new ComponentName(
                        this,
                        icon_tag_1212);
                //正常图标新状态
                int actNewState = useCode == 1 ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                        : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
                if (useCode == 1) {//新状态跟当前状态不一样才执行


                    //去除旧图标，不去除的话会出现2个App图标
                    pm.setComponentEnabledSetting(getComponentName(),
                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                            PackageManager.DONT_KILL_APP);
                    pm.setComponentEnabledSetting(
                            actComponentName,
                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                            PackageManager.DONT_KILL_APP);


                }

            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }
}
